﻿using FluentMigrator.Runner;
using FluentMigrator.Runner.Initialization;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CPlatePrintSys.Server.App_Start
{
    public static class MigrationConfig
    {
        public static void Initialize()
        {
            try
            {
                // 构建服务容器
                var serviceProvider = CreateServices();

                // 使用服务容器执行迁移
                using (var scope = serviceProvider.CreateScope())
                {
                    UpdateDatabase(scope.ServiceProvider);
                }
            }
            catch (Exception ex)
            {
                // 记录启动时的迁移错误
                System.Diagnostics.Trace.TraceError("数据库迁移执行失败: " + ex.Message);
                throw;
            }
        }

        private static IServiceProvider CreateServices()
        {
            // 获取数据库连接字符串
            string connectionString = System.Configuration.ConfigurationManager
                .ConnectionStrings["DefaultConnection"]?.ConnectionString;

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new InvalidOperationException("数据库连接字符串未配置");
            }

            return new ServiceCollection()
                // 添加FluentMigrator服务
                .AddFluentMigratorCore()
                .ConfigureRunner(rb => rb
                    // 添加MySql支持
                    .AddMySql5()
                    // 设置连接字符串
                    .WithGlobalConnectionString(connectionString)
                    // 扫描迁移程序集
                    .ScanIn(typeof(MigrationConfig).Assembly).For.Migrations()
                )
                .Configure<RunnerOptions>(options=>
                {
                   
                })
                // 添加日志记录
                .AddLogging(lb => lb.AddFluentMigratorConsole())
                .BuildServiceProvider(false);
        }

        private static void UpdateDatabase(IServiceProvider serviceProvider)
        {
            // 解析迁移运行器
            var runner = serviceProvider.GetRequiredService<IMigrationRunner>();

            // 执行所有未应用的迁移
            runner.MigrateUp();
        }
    }
}